#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash nwchem-6.8.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules time patch libatomic autoconf automake libtool numactl binutils systemd-devel wget
set -e

wget -t 10 -c -P $buildpath https://github.com/nwchemgit/nwchem/archive/refs/tags/6.8.1-release.tar.gz
tar -xvf $buildpath/6.8.1-release.tar.gz -C $buildpath && rm -rf $buildpath/6.8.1-release.tar.gz
export CC=`which clang`
export CXX=`which clang++`
export FC=`which flang`
cd $buildpath/nwchem-6.8.1-release
cd src/tools
wget -t 10 -c https://github.com/edoapra/ga/releases/download/v5.6.5/ga-5.6.5.tar.gz
tar -zxvf ga-5.6.5.tar.gz
export NWCHEM_TOP=$buildpath/nwchem-6.8.1-release
export NWCHEM_TARGET=LINUX64
export NWCHEM_MODULES=all
export USE_MPI=y
export USE_INTERNALBLAS=y
cd $buildpath/nwchem-6.8.1-release/src
make -j$(nproc)
mkdir -p $installpath/nwchem-6.8.1 && cp -r $buildpath/nwchem-6.8.1-release/* $installpath/nwchem-6.8.1
cat>"$installpath/nwchem-6.8.1/nwchem_modulefiles"<<EOF
#%Module1.0
conflict nwchem
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set NWCHEM \$pwd
setenv NWCHEM \$NWCHEM
prepend-path PATH \$NWCHEM/bin/LINUX64
prepend-path NWCHEM_BASIS_LIBRARY \$NWCHEM/src/basis/libraries/
EOF

rm -rf $buildpath/nwchem-6.8.1-release
